﻿using Dapper;
using Inventorycount.API.Read.Application.Command;
using Inventorycount.Domain;
using Inventorycount.ErrorCode;
using MediatR;
using System.Data;
using System.Text;

namespace Inventorycount.API.Read.Application.CommandHandLer
{
    public class GetoutboundorderCommandHandLer : IRequestHandler<GetoutboundorderCommand, APIPaing<Wms_outbound_order>>
    {
        private readonly IDbConnection repository;

        public GetoutboundorderCommandHandLer(IDbConnection repository)
        {
            this.repository = repository;
        }
        public async Task<APIPaing<Wms_outbound_order>> Handle(GetoutboundorderCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaing<Wms_outbound_order>
            {
                Code = ResultCode.Ok,
                Message = "查询成功",
                Data = new List<Wms_outbound_order>()
            };

            try
            {
                // 构建基础查询
                var sql = new StringBuilder(@"
                    SELECT 
                         Id,
                        Outbound_code ,
                        Transfer_id,
                        Warehouse_id,
                        Status,
                        Operator_id,
                        Operate_time,
                        Remark
                    FROM Wms_outbound_order ");

                var parameters = new DynamicParameters();
                // 3. 修正分页查询
                sql.Append(" ORDER BY Operate_time DESC");
                sql.Append(" LIMIT @Offset, @PageSize");
                parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);
                parameters.Add("PageSize", request.PageSize);
                // 4. 修正COUNT查询
                var countSql = new StringBuilder(@"
            SELECT COUNT(DISTINCT Id) 
            FROM Wms_inbound_order 
             ");

                // 执行查询
                var count = await repository.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                // 执行查询
                var log = await repository.QueryAsync<Wms_outbound_order>(sql.ToString(), parameters);

                result.Data = log.ToList();
                result.TotalCount = count;
                result.TotalPage = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                result.Message = "查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
}
